﻿using System;
using System.Text;
using System.Data;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BudgetSV.Common;
using System.Linq;
using System.Linq.Expressions;
using BudgetData;
using LinqKit;

namespace BudgetSV.admin.manager
{
    public partial class manager_list : ManagePage
    {
        protected int totalCount;
        protected int page;
        protected int pageSize;

        protected string keywords = string.Empty;
        protected string role = string.Empty;
        protected string department = string.Empty;

        protected ManagerRole[] m_roles;

        protected Organization[] m_orgs;

        protected Department[] m_depts;

        protected Manager model;

        protected void Page_Load(object sender, EventArgs e)
        {
            this.keywords = DTRequest.GetQueryString("keywords");
            this.role = DTRequest.GetQueryString("role");
            this.department = DTRequest.GetQueryString("dept");

            this.pageSize = GetPageSize(10); //每页数量
            if (!Page.IsPostBack)
            {
                ChkAdminLevel("manager_list", DTEnums.ActionEnum.View.ToString()); //检查权限

                //model = Session[DTKeys.SESSION_ADMIN_INFO] as Manager;
                model = GetAdminInfo(); //取得当前管理员信息

                InitDic();
                //RptBind("role_type>=" + model.role_type + CombSqlTxt(keywords) + BlongOrg(), "depart_id,user_name");

                //var expr = CombSqlTxt(keywords, role, department);
                //expr = expr.And(BlongOrg(model.org_id));
                //RptBind(expr, "sort,depart_id,user_name");
                RptBind(model.org_id);
            }
        }

        #region 数据绑定=================================

        /// <summary>
        /// 准备字典数据
        /// </summary>
        protected void InitDic()
        {
            var user = GetAdminInfo();

            m_roles = Mod.GetList<ManagerRole>(r => r.org_id == user.org_id || r.org_id == 0).ToArray();
            PageClass.BindComboBox(ddlRole, m_roles, "role_name", "id", "全部角色");
            if (!string.IsNullOrEmpty(role)) ddlRole.SelectedValue = role;

            m_orgs = Mod.GetList<Organization>(c=>true).ToArray();

            m_depts = GetDepartList(user.org_id).ToArray();
            PageClass.BindComboBox(ddlDepartment, m_depts, "name", "id", "全部处室");
            if (!string.IsNullOrEmpty(department)) ddlDepartment.SelectedValue = department;
        }

        /// <summary>
        /// 得到角色名
        /// </summary>
        /// <param name="iRoleId"></param>
        /// <returns></returns>
        protected string GetRole(int managerid)
        {
            List<ManagerRole> rls= Mod.GetList<ManagerRole>("select * from ManagerRole where id in (SELECT role_id from ManagerRoleLK WHERE manager_id="+ managerid + ")");
            string result = ""; ;
            foreach (var r in rls) {
                result += r.role_name + ",";
            }
            if (result.Length > 1) { result = result.Substring(0, result.Length - 1); }
            return result;
        }

        /// <summary>
        /// 得到机构名
        /// </summary>
        /// <param name="iDeptId"></param>
        /// <returns></returns>
        protected string GetOrg(long ideptId)
        {
            if (m_orgs != null)
            {
                var role = m_orgs.FirstOrDefault(r => r.id == ideptId);
                if (role != null) return role.name;
            }

            return string.Empty;
        }

        /// <summary>
        /// 得到部门名
        /// </summary>
        /// <param name="iDeId"></param>
        /// <returns></returns>
        protected string GetDeparment(long ideId)
        {
            if (m_depts != null)
            {
                var role = m_depts.FirstOrDefault(r => r.id == ideId);
                if (role != null) return role.name;
            }

            return string.Empty;
        }


        private void RptBind(long orgid)
        {
            this.page = DTRequest.GetQueryInt("page", 1);
            txtKeywords.Text = this.keywords;
            //keywords, role, department
            //this.rptList.DataSource = Mod.GetList<Manager>(where, this.pageSize, this.page,  _orderby, out this.totalCount);
            string sql = "select * from Manager where (org_id = " + orgid + " or creator_org =" + orgid + ") ";
            if (!string.IsNullOrEmpty(keywords)) {
                sql += " and (user_name like  '%" + keywords + "%' or real_name like '%" + keywords + "%' or email like '%" + keywords + "%') ";
            }
            long roleId = 0;
            if (long.TryParse(role, out roleId))
            {
                sql += " and id in (SELECT manager_id from ManagerRoleLK WHERE role_id="+ roleId + " ) ";
            }
            long deptId = 0;
            if (long.TryParse(department, out deptId))
            {
                sql += " and depart_id=" + deptId + "  ";
            }
            var ls = Mod.GetList<Manager>(sql, page, pageSize, out totalCount);
            this.rptList.DataSource = ls;
            this.rptList.DataBind();

            //绑定页码
            txtPageNum.Text = this.pageSize.ToString();
            string pageUrl = Utils.CombUrlTxt("manager_list.aspx", "keywords={0}&page={1}&role={2}&dept={3}", 
                this.keywords, "__id__", this.role, this.department);
            PageContent.InnerHtml = Utils.OutPageList(this.pageSize, this.page, this.totalCount, pageUrl, 8);
        }

        #endregion

        #region 组合SQL查询语句==========================
        
        #endregion

        #region 返回每页数量=============================
        private int GetPageSize(int _default_size)
        {
            int _pagesize;
            if (int.TryParse(Utils.GetCookie("manager_page_size"), out _pagesize))
            {
                if (_pagesize > 0)
                {
                    return _pagesize;
                }
            }
            return _default_size;
        }
        #endregion

        //关健字查询
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            Response.Redirect(Utils.CombUrlTxt("manager_list.aspx", "keywords={0}", txtKeywords.Text));
        }

        protected void ddlRole_SelectedIndexChanged(object sender, EventArgs e)
        {
            Response.Redirect(Utils.CombUrlTxt("manager_list.aspx", "keywords={0}&role={1}&dept={2}",
                this.keywords, ddlRole.SelectedValue, this.department));
        }

        protected void ddlDepartment_SelectedIndexChanged(object sender, EventArgs e)
        {
            Response.Redirect(Utils.CombUrlTxt("manager_list.aspx", "keywords={0}&role={1}&dept={2}",
                this.keywords, this.role, ddlDepartment.SelectedValue));
        }

        //设置分页数量
        protected void txtPageNum_TextChanged(object sender, EventArgs e)
        {
            int _pagesize;
            if (int.TryParse(txtPageNum.Text.Trim(), out _pagesize))
            {
                if (_pagesize > 0)
                {
                    Utils.WriteCookie("manager_page_size", _pagesize.ToString(), 14400);
                }
            }
            Response.Redirect(Utils.CombUrlTxt("manager_list.aspx", "keywords={0}&role={1}&dept={2}", 
                this.keywords, this.role, this.department));
        }

        //批量删除
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            ChkAdminLevel("manager_list", DTEnums.ActionEnum.Delete.ToString()); //检查权限

            int sucCount = 0;
            int errorCount = 0;
            for (int i = 0; i < rptList.Items.Count; i++)
            {
                long id = Convert.ToInt32(((HiddenField)rptList.Items[i].FindControl("hidId")).Value);
                CheckBox cb = (CheckBox)rptList.Items[i].FindControl("chkId");
                if (cb.Checked)
                {
                    int iPatentCount = 1;   // new BLL.PatentBLL().Count(p => p.sub_manager_id == id);
                    int iPlanCount = 1;     // new BLL.PatentPlanBLL().Count(p => p.addmanid == id);

                    //if (iPatentCount > 0 || iPlanCount > 0)
                    //{
                    //    errorCount++;
                    //}
                    //else
                    {
                        if (Mod.Delete<Manager>(c=>c.id==id)>0)
                        {
                            sucCount += 1;
                        }
                        else
                        {
                            errorCount += 1;
                        }
                    }
                }
            }
            AddAdminLog(DTEnums.ActionEnum.Delete.ToString(), "删除管理员" + sucCount + "条，失败" + errorCount + "条"); //记录日志
            JscriptMsg("删除成功" + sucCount + "条，失败" + errorCount + "条！", Utils.CombUrlTxt("manager_list.aspx", "keywords={0}&role={1}&dept={2}", 
                this.keywords, this.role, this.department), "Success");
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < rptList.Items.Count; i++)
            {
                long id = Convert.ToInt32(((HiddenField)rptList.Items[i].FindControl("hidId")).Value);
                int sortId;
                if (!int.TryParse(((TextBox)rptList.Items[i].FindControl("txtSortId")).Text.Trim(), out sortId))
                {
                    sortId = 99;
                }
                var m = Mod.GetModel<Manager>(c => c.id == id);
                m.sort = sortId;
                Mod.Update(m);
            }
            AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "保存导航排序"); //记录日志
            JscriptMsg("保存排序成功！", "nav_list.aspx", "Success", "parent.loadMenuTree(true)");
        }
    }
}